package com.rem.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * 发送数据到kafka
 * 带回调
 *
 * @author Rem
 * @date 2022-12-28
 */
public class CustomerProducerCallback {

    public static void main(String[] args) throws InterruptedException {
        Properties properties = new Properties();
        //连接kafka
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9093,localhost:9094,localhost:9095");

        //配置kafka连接器以及key value序列化方式
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties, new StringSerializer(), new StringSerializer());

        for (int i = 0; i < 100; i++) {
            kafkaProducer.send(new ProducerRecord<>("rangeTest", "hello" + i), (metadata, exception) -> {
                if (exception == null) {
                    System.out.println("主题： " + metadata.topic() + " 分区： " + metadata.partition());
                }
            });
            //延迟一会会看到数据发往不同分区
            TimeUnit.MILLISECONDS.sleep(10);
        }
        kafkaProducer.close();
    }
}
